package ld.servlet;

import com.alibaba.fastjson.JSON;
import ld.pojo.Dept;
import ld.service.DeptService;
import ld.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @Author: Liudao
 * @Date: 2022-08-04-17:39
 * @Description:
 */
@WebServlet("/dept")
public class DeptServlet extends HttpServlet {
    @Autowired
    private DeptService deptService;

    @Override
    public void init()  {
        WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        deptService = webApplicationContext.getBean(DeptService.class);

    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws  IOException {
        //1.1 处理中文乱码
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
        //1.2 得到请求参数，根据参数调用方法
        String cmd = req.getParameter("cmd");
        if(!StringUtils.isEmpty(cmd)){
            if("list".equals(cmd)){             //1.3 查询部门列表
                list(req,resp);
            }
        }
    }

    private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //1.1 查询所有部门
        List<Dept> all = deptService.findAll();
        //1.2 输出到页面
        R r = R.ok().data("list", all);
        resp.getWriter().println(JSON.toJSONString(r));
        //1.3 刷新
        resp.getWriter().flush();
    }
}
